package com.zy.service.bs.impl;

import com.zy.pojo.exceptions.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zy.dao.bs.CarDao;
import com.zy.entity.enums.StatusEnum;
import com.zy.entity.bs.Car;
import com.zy.pojo.query.bs.CarQuery;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.CarService;
import com.zy.utils.DateUtil;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service("carService")
public class CarServiceImpl extends BaseServiceImpl<Car> implements CarService {

	@Autowired
	private CarDao carDao;

	@Override
	public PageVo pageCar(CarQuery carQuery, Integer start, Integer limit) {
		return new PageVo(start, limit, this.carDao.countCar(carQuery), this.carDao.listCar(carQuery, start, limit));
	}

	@Override
	public void saveCar(Car car) {
		car.setId(null);
		existsName(car);
		long time = DateUtil.getTime();
		car.setCreateTime(time);
		car.setModifyTime(time);
		car.setStatus(StatusEnum.NORMAL.getValue());
		this.carDao.save(car);
	}
	
	@Override
	public void updateCar(Car car) {
		existsName(car);
		car.setModifyTime(DateUtil.getTime());
		this.carDao.updateByPrimaryKeySelective(car);
	}

	@Override
	public void removeCar(long id) {
		try {
			this.carDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			Car car = new Car();
			car.setId(id);
			car.setModifyTime(DateUtil.getTime());
			car.setStatus(StatusEnum.DELETE.getValue());
			this.carDao.updateByPrimaryKeySelective(car);
		}
	}

	@Override
	public void recover(long id) {
		Car car = new Car();
		car.setId(id);
		car.setModifyTime(DateUtil.getTime());
		car.setStatus(StatusEnum.NORMAL.getValue());
		this.carDao.updateByPrimaryKeySelective(car);
	}

	@Override
	public List<Car> getListCars(Long userId) {
		return carDao.getListCars(userId);
	}

	private void existsName(Car car) {
		Example ex = new Example(Car.class);
		Example.Criteria cr = ex.createCriteria();
		cr.andEqualTo("name", car.getName());
		cr.andEqualTo("carTypeId", car.getCarTypeId());
		Car pojo = carDao.getByExample(ex);
		if (pojo != null && !pojo.getId().equals(car.getId())) {
			throw new ServiceException(car.getName()+"重复车型系");
		}

	}

}
